<template>
  <div class="form-setting-panel form-logistics-setting">
    <!-- start 标题 -->
    <div class="form-setting-group form-common-setting">
      <h3 class="form-setting-panel-title">
        {{ field.displayName }}
        <span class="form-type-text">{{ $t('common.base.payComponent') }}</span>
      </h3>
      <div class="form-design-warning">
        <span>{{ $t('common.form.tip.logistics.tips2') }}<span class="link-text" @click="jumpToUsage">{{ $t('common.form.tip.logistics.tips8') }}。</span></span>
      </div>
    </div>
    <!-- end 标题 -->

    <!-- start 物流公司选择 -->
    <div class="form-setting-group form-data-source-setting">
      <h4 class="form-item-title">{{ $t('common.base.logisticsCompany') }}</h4>
      <el-select class="w100" :value="type" @change="handleSelectType">
        <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
      </el-select>
    </div>
    <!-- end 物流公司选择 -->

    <!-- start 自定义指定物流公司选项 -->
    <div class="form-setting-group mt12" v-show="type === 1">
      <h4>{{ $t('common.base.option') }}</h4>
      <div class="form-select-setting-list">
        <draggable tag="div" class="list-group" :list="activeLogistics" v-bind="{ animation: 380 }" handle=".handle" @update="update">
          <div v-for="(option, index) of activeLogistics" :key="option.id" class="form-select-setting-option">
            <button type="button" class="btn-text handle">
              <i class="iconfont icon-tuozhuaipaixu"></i>
            </button>

            <template>
              <el-select v-if="addLogisticsDisabled && !option.name" class="add-select" v-model="selectLogistics" :filterable="true" :disabled="selectLogisticsDisabled" @change="handleSelectAdd" :placeholder="$t('common.form.tip.chooseBeforeTips', { module: $t('common.base.logisticsCompany') })">
                <el-option v-for="logistics of showLogisticsCompany" :key="logistics.id" :value="logistics" :label="logistics.name"></el-option>
              </el-select>

              <input v-else type="text" readonly v-model="option.name" />
            </template>

            <button type="button" class="btn-text form-select-setting-delete" @click="delLogistics(option, index)">
              <i class="iconfont icon-minus-fill"></i>
            </button>
            <template>
              <button type="button" class="btn-text form-select-setting-default" :class="[defaultLogistics && defaultLogistics.id === option.id && 'btn-active']" @click="setDefaultLogistics(option)">
                <i class="iconfont icon-check-fill"></i>
              </button>
              <span class="form-select-setting-defaultValue" v-if="option.isDefault">{{ $t('common.base.default') }}</span>
            </template>
          </div>
        </draggable>
      </div>
      <div class="form-select-setting-operation form-select-setting-btnbox">
        <button type="button" class="btn-text" :disabled="addLogisticsDisabled" @click="addLogistics">
          {{ $t('common.base.addOption') }}
        </button>
      </div>

      <!-- <el-select
        class="add-select"
        v-model="selectLogistics"
        :filterable="true"
        :disabled="selectLogisticsDisabled"
        @change="handleSelectAdd"
        placeholder="请选择物流公司"
      >
        <el-option
          v-for="logistics of showLogisticsCompany"
          :key="logistics.id"
          :value="logistics"
          :label="logistics.name"
        ></el-option>
      </el-select> -->
    </div>
    <!-- end 自定义指定物流公司选项 -->

    <!-- start 字段权限 -->
    <div class="form-setting-group form-setting-item">
      <h4 class="form-item-title">{{ $t('common.base.fieldPermissions') }}</h4>
      <div class="form-item-box">
        <!-- 移动端列表展示 -->
        <!-- <mobile-show-setting :is-task-mode="isTaskMode" :is-event-mode="isEventMode" v-if="isOnlyEventMode || isOnlyTaskMode" :field="field" :fields="fields" @input="updateForAuth"></mobile-show-setting> -->
        <!-- 可见性 -->
        <form-visible-setting :field="field" @input="updateForAuth"></form-visible-setting>
        <!-- 支持高级搜索 -->
        <form-search-setting :field="field" @input="updateForAuth"></form-search-setting>
        <!-- 是否对客户可见 -->
        <form-visible-customer-setting :field="field" @input="updateForAuth" v-if="isShowVisibleCustomer"></form-visible-customer-setting>
      </div>
    </div>
    <!-- end 字段权限 -->

    <!-- start 使用权限 -->
    <div class="form-setting-group mt12 form-data-source-setting">
      <h4 class="form-item-title">{{ $t('common.base.usrPermissions') }}</h4>
      <el-checkbox v-model="canCheckForStaff" :true-label="1" :false-label="0" @change="update">
        {{ $t('common.form.tip.logistics.tips3') }}
      </el-checkbox>
      <el-checkbox v-if="allowCustomLook" v-model="canCheckForCustom" :true-label="1" :false-label="0" @change="update">
        {{ $t('common.form.tip.logistics.tips4') }}
      </el-checkbox>
    </div>
    <!-- end 使用权限 -->
    <!-- start 其他设置 -->
    <div class="form-setting-group form-setting-item">
      <h4 class="form-item-title">{{ $t('common.base.otherSet') }}</h4>
      <div class="form-item-box" v-if="allowPublicSet">
        <!-- 设为公用字段 -->
        <form-public-setting :field="field" @input="update"></form-public-setting>
      </div>

      <el-checkbox v-model="isScanCode" @input="update" :true-label="1" :false-label="0">
        {{ $t('common.form.preview.text.des1') }}
        <el-tooltip :content="$t('common.form.preview.text.des2')" placement="top">
          <i class="iconfont icon-question"></i>
        </el-tooltip>
      </el-checkbox>
    </div>
    <!-- end 其他设置 -->
    <!-- start 校验 -->
    <div class="form-setting-group form-setting-item">
      <h4 class="form-item-title">{{ $t('common.base.check') }}</h4>
      <div class="form-item-box">
        <!-- 必填 -->
        <form-required-setting :field="field" @input="update"></form-required-setting>
      </div>
    </div>
    <!-- end 校验 -->
  </div>
</template>

<script>
import { getLogisticsCompanyList } from '@src/api/FieldApi';
import propSet, { settingProps } from '@src/component/form/components/props';
import draggable from 'vuedraggable';
import Platform from '@src/platform';

import SettingMixin from '@src/component/form/mixin/setting';
import { isEmpty } from '@src/util/type';
import i18n from '@src/locales';
import { jumpToUsage } from '@src/util/business/openTab.js'

const TypeOptions = [
  { label: i18n.t('common.base.allOfModule', { module: i18n.t('common.base.logisticsCompany') }), value: 0 },
  { label: i18n.t('common.base.appointOfModule', { module: i18n.t('common.base.logisticsCompany') }), value: 1 },
];

export default {
  name: 'form-logistics-setting',
  components: { draggable },
  mixins: [SettingMixin],
  props: {
    field: propSet.field,
    /** 用于获取FormDesign实例 */
    getContext: Function,
    ...settingProps,
  },
  data() {
    return {
      typeOptions: Object.freeze(TypeOptions),
      type: 0,
      logisticsCompany: [],
      activeLogistics: [],
      defaultLogistics: null,
      canCheckForStaff: 0,
      canCheckForCustom: 0,
      selectLogistics: null,
      prevFiled: null,
      isScanCode: 0,
    };
  },
  computed: {
    addLogisticsDisabled() {
      return this.activeLogistics.some(item => !item?.id);
    },
    selectLogisticsDisabled() {
      return !this.addLogisticsDisabled;
    },
    // 候选物流公司
    showLogisticsCompany() {
      const ids = new Set(this.activeLogistics.map(v => v.id));
      return ids.size ? this.logisticsCompany.filter(({ id }) => !ids.has(id)) : this.logisticsCompany;
    },
  },
  watch: {
    field(newValue, oldValue) {
      if (this.prevFiled?.fieldName !== newValue.fieldName) {
        this.prevFiled = newValue;
        this.initialize();
      }
    },
  },
  mounted() {
    this.initialize();
  },
  methods: {
    // 页面初始化
    async initialize() {
      const { setting } = this.field;

      const defaultValue = setting?.defaultValue || {};

      await this.fetchLogisticsCompany();
      if (!Object.keys(setting).length) {
        // 新建组件
        this.update();
      } else {
        // 编辑组件
        const { dataSource, dataSourceType, canCheckForStaff, canCheckForCustom, isScanCode } = setting;

        this.type = dataSourceType;
        this.canCheckForStaff = canCheckForStaff;
        this.canCheckForCustom = canCheckForCustom;
        this.isScanCode = isScanCode || 0;
        if (dataSourceType === 1) {
          // 指定物流 初始化选中的物流列表
          this.activeLogistics = dataSource;

          if (defaultValue?.id) {
            this.setDefaultLogistics(defaultValue);
          }
        }

        if (isEmpty(this.activeLogistics)) {
          this.addLogistics();
        }
      }
    },
    // 查询所有物流公司
    async fetchLogisticsCompany() {
      try {
        const list = await getLogisticsCompanyList();
        this.logisticsCompany = list;
      } catch (error) {
        console.error('获取物流公司失败', error);
      }
    },
    /**
     * 切换物流选择模式
     */
    handleSelectType(type) {
      this.type = type;
      this.update();
    },
    /**
     * 删除一个已选择的指定物流
     */
    delLogistics(logistics, index) {
      if (this.defaultLogistics && logistics) {
        this.defaultLogistics = null;
      }
      this.activeLogistics.splice(index, 1);
      this.update();
    },
    /**
     * 设置一个指定物流为默认物流
     */
    setDefaultLogistics(logistics) {
      if (!logistics.id) return Platform.alert(this.$t('common.form.tip.fullOfOptionsTips'));

      const isSameLogistics = this.defaultLogistics?.id == logistics?.id;
      this.defaultLogistics = isSameLogistics ? null : logistics;

      this.update();
    },

    // 添加一个指定物流
    handleSelectAdd(value) {
      const emptyIndex = this.activeLogistics.findIndex(item => !item?.id);
      this.activeLogistics.splice(emptyIndex, 1, value);
      this.selectLogistics = null;

      this.update();
    },

    updateForAuth(value, prop, isSetting = false) {
      this.$emit('input', { value, prop, isSetting });
      this.update();
    },
    update(value, prop, isSetting = false) {
      const { type, activeLogistics, defaultLogistics, canCheckForStaff, canCheckForCustom, isScanCode } = this;

      const originSetting = this.field?.setting || {};

      const setting = {
        ...originSetting,
        dataSourceType: type,
        dataSource: type === 0 ? null : activeLogistics,
        defaultValue: defaultLogistics || null,
        canCheckForStaff,
        canCheckForCustom,
        isScanCode,
      };

      if (prop === 'isNull') {
        this.$emit('input', {prop, value});
      }

      this.$emit('input', {
        prop: 'setting',
        value: setting,
      });

      if (prop === 'isPublic') {
        this.$emit('input', { value, prop, isSetting });
      }
    },
    addLogistics() {
      this.activeLogistics.push({
        name: '',
        id: null,
      });
      this.update();
    },
    jumpToUsage() {
      jumpToUsage('logisticsQuery');
    }
  },
};
</script>

<style lang="scss" scope>
.btn-text {
  &:disabled {
    cursor: not-allowed;
    color: #999 !important;
  }
}
.add-select {
  width: 185px;
}

.form-setting-panel-title {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .form-type-text {
    display: inline-block;
    color: #ff9200;
    background-color: #fff2e0;
    font-weight: normal;
  }
}
</style>

<style lang="scss">
.form-logistics-setting {
  .form-select-setting-delete {
    color: $color-danger;
    .iconfont {
      color: $color-danger;
    }
  }
}

.form-select-setting-operation {
  button[disabled] {
    opacity: 0.4;
  }
}
</style>
